<!DOCTYPE html>
<html>

<head><meta name="generator" content="Hexo 3.8.0">
  
  <title>何为Promise - 绪锋</title>
  <meta charset="UTF-8">
  <meta name="description" content="小镇青年,心怀远方">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  
  

    <!-- Site Verification -->
    <meta name="baidu-site-verification" content="cXpXJOvmtY">

  <link rel="shortcut icon" href="/images/favicon.ico" type="image/x-icon">
  <meta name="description" content="Promise 是进行异步操作的构造函数。Promise 对象用于表示一个异步操作的最终完成 (或失败), 及其结果值.">
<meta name="keywords" content="JS">
<meta property="og:type" content="article">
<meta property="og:title" content="何为Promise">
<meta property="og:url" content="https://mraing.github.io/2020/04/11/何为Promise/index.html">
<meta property="og:site_name" content="绪锋">
<meta property="og:description" content="Promise 是进行异步操作的构造函数。Promise 对象用于表示一个异步操作的最终完成 (或失败), 及其结果值.">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2021-03-30T01:13:28.811Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="何为Promise">
<meta name="twitter:description" content="Promise 是进行异步操作的构造函数。Promise 对象用于表示一个异步操作的最终完成 (或失败), 及其结果值.">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/mdui@0.4.3/dist/css/mdui.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@9.15.8/styles/atom-one-dark.css">
   
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css">
  
  
  <link rel="stylesheet" href="//at.alicdn.com/t/font_1038733_0xvrvpg9c0r.css">
  <link rel="stylesheet" href="/css/style.css?v=1627371788797">
</head>

<body class="mdui-drawer-body-left">
  
  <div id="nexmoe-background">
    <div class="nexmoe-bg" style="background-image: url(https://i.loli.net/2019/01/13/5c3aec85a4343.jpg)"></div>
    <div class="mdui-appbar mdui-shadow-0">
      <div class="mdui-toolbar">
        <a mdui-drawer="{target: '#drawer', swipe: true}" title="menu" class="mdui-btn mdui-btn-icon"><i class="mdui-icon material-icons">menu</i></a>
        <div class="mdui-toolbar-spacer"></div>
        <!--<a href="javascript:;" class="mdui-btn mdui-btn-icon"><i class="mdui-icon material-icons">search</i></a>-->
        <a href="/" title="LeeGeing" class="mdui-btn mdui-btn-icon"><img src="/images/avatar.jpg"></a>
       </div>
    </div>
  </div>
  <div id="nexmoe-header">
      <div class="nexmoe-drawer mdui-drawer" id="drawer">
    <div class="nexmoe-avatar mdui-ripple">
        <a href="/" title="LeeGeing">
            <img src="/images/avatar.jpg" alt="LeeGeing">
        </a>
    </div>
    <div class="nexmoe-count">
        <div><span>文章</span>82</div>
        <div><span>标签</span>28</div>
        <div><span>分类</span>8</div>
    </div>
    <ul class="nexmoe-list mdui-list" mdui-collapse="{accordion: true}">
        
        <a class="nexmoe-list-item mdui-list-item mdui-ripple" href="/" title="回到首页">
            <i class="mdui-list-item-icon nexmoefont icon-home"></i>
            <div class="mdui-list-item-content">
                回到首页
            </div>
        </a>
        
        <a class="nexmoe-list-item mdui-list-item mdui-ripple" href="/about.html" title="关于博客">
            <i class="mdui-list-item-icon nexmoefont icon-info-circle"></i>
            <div class="mdui-list-item-content">
                关于博客
            </div>
        </a>
        
        <a class="nexmoe-list-item mdui-list-item mdui-ripple" href="/PY.html" title="我的朋友">
            <i class="mdui-list-item-icon nexmoefont icon-unorderedlist"></i>
            <div class="mdui-list-item-content">
                我的朋友
            </div>
        </a>
        
    </ul>
    <aside id="nexmoe-sidebar">
  
  <div class="nexmoe-widget-wrap">
    <h3 class="nexmoe-widget-title">社交按钮</h3>
    <div class="nexmoe-widget nexmoe-social">
        <a class="mdui-ripple" href="https://space.bilibili.com/11147795" target="_blank" mdui-tooltip="{content: '哔哩哔哩'}" style="color: rgb(231, 106, 141);background-color: rgba(231, 106, 141, .15);">
            <i class="nexmoefont icon-bilibili"></i>
        </a><a class="mdui-ripple" href="https://github.com/mraing/" target="_blank" mdui-tooltip="{content: 'GitHub'}" style="color: rgb(25, 23, 23);background-color: rgba(25, 23, 23, .15);">
            <i class="nexmoefont icon-github"></i>
        </a>
    </div>
</div>
  
  
  <div class="nexmoe-widget-wrap">
    <h3 class="nexmoe-widget-title">文章分类</h3>
    <div class="nexmoe-widget">

      <ul class="category-list">

        


        

        

        <li class="category-list-item">
          <a class="category-list-link" href="/categories/React/">React</a>
          <span class="category-list-count">7</span>
        </li>

        

        <li class="category-list-item">
          <a class="category-list-link" href="/categories/TypeScript/">TypeScript</a>
          <span class="category-list-count">5</span>
        </li>

        

        <li class="category-list-item">
          <a class="category-list-link" href="/categories/Vue/">Vue</a>
          <span class="category-list-count">33</span>
        </li>

        

        <li class="category-list-item">
          <a class="category-list-link" href="/categories/前端/">前端</a>
          <span class="category-list-count">19</span>
        </li>

        

        <li class="category-list-item">
          <a class="category-list-link" href="/categories/博客/">博客</a>
          <span class="category-list-count">3</span>
        </li>

        

        <li class="category-list-item">
          <a class="category-list-link" href="/categories/工具/">工具</a>
          <span class="category-list-count">6</span>
        </li>

        

        <li class="category-list-item">
          <a class="category-list-link" href="/categories/碎碎念/">碎碎念</a>
          <span class="category-list-count">4</span>
        </li>

        

        <li class="category-list-item">
          <a class="category-list-link" href="/categories/软件设计师/">软件设计师</a>
          <span class="category-list-count">5</span>
        </li>

        
      </ul>

    </div>
  </div>


  
  
  <div class="nexmoe-widget-wrap">
    <h3 class="nexmoe-widget-title">标签云</h3>
    <div id="randomtagcloud" class="nexmoe-widget tagcloud">
      <a href="/tags/Hbuilder/" style="font-size: 10px;">Hbuilder</a> <a href="/tags/Homebrew/" style="font-size: 10px;">Homebrew</a> <a href="/tags/JS/" style="font-size: 14px;">JS</a> <a href="/tags/JSX/" style="font-size: 10px;">JSX</a> <a href="/tags/Mint-UI/" style="font-size: 10px;">Mint-UI</a> <a href="/tags/Nginx/" style="font-size: 10px;">Nginx</a> <a href="/tags/Ngnix/" style="font-size: 10px;">Ngnix</a> <a href="/tags/OpenInTerminal/" style="font-size: 10px;">OpenInTerminal</a> <a href="/tags/Sass/" style="font-size: 14px;">Sass</a> <a href="/tags/Vuex/" style="font-size: 10px;">Vuex</a> <a href="/tags/antd/" style="font-size: 10px;">antd</a> <a href="/tags/css/" style="font-size: 10px;">css</a> <a href="/tags/docsify/" style="font-size: 10px;">docsify</a> <a href="/tags/git/" style="font-size: 12px;">git</a> <a href="/tags/hexo/" style="font-size: 12px;">hexo</a> <a href="/tags/mui/" style="font-size: 18px;">mui</a> <a href="/tags/react/" style="font-size: 14px;">react</a> <a href="/tags/redux/" style="font-size: 10px;">redux</a> <a href="/tags/swiper/" style="font-size: 10px;">swiper</a> <a href="/tags/typescript/" style="font-size: 16px;">typescript</a> <a href="/tags/vue/" style="font-size: 20px;">vue</a> <a href="/tags/vux/" style="font-size: 10px;">vux</a> <a href="/tags/她/" style="font-size: 10px;">她</a> <a href="/tags/感悟/" style="font-size: 12px;">感悟</a> <a href="/tags/日记/" style="font-size: 10px;">日记</a> <a href="/tags/消息推送/" style="font-size: 10px;">消息推送</a> <a href="/tags/知识点/" style="font-size: 10px;">知识点</a> <a href="/tags/软考笔记/" style="font-size: 16px;">软考笔记</a>
    </div>
    
  </div>

  
  
  <div class="nexmoe-widget-wrap">
    <h3 class="nexmoe-widget-title">文章归档</h3>
    <div class="nexmoe-widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/07/">七月 2021</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/03/">三月 2021</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/10/">十月 2020</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/09/">九月 2020</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/07/">七月 2020</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/06/">六月 2020</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/04/">四月 2020</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/01/">一月 2020</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/12/">十二月 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/09/">九月 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/08/">八月 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/07/">七月 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/06/">六月 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/05/">五月 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/04/">四月 2019</a></li></ul>
    </div>
  </div>


  
</aside>
    <!-- <div class="nexmoe-copyright">
        &copy; 2021 LeeGeing
        Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>
        & <a href="https://nexmoe.com/hexo-theme-nexmoe.html" target="_blank">Nexmoe</a>
    </div> -->
    <div class="nexmoe-copyright">
        <a href="http://beian.miit.gov.cn/state/outPortal/loginPortal.action" target="_blank">湘ICP备16019481号</a>
        <!-- & <a href="https://nexmoe.com/hexo-theme-nexmoe.html" target="_blank">Nexmoe</a> -->
    </div>
</div><!-- .nexmoe-drawer -->
  </div>
  <div id="nexmoe-content">
    <div class="nexmoe-primary">
        <div class="nexmoe-post">
    <div class="nexmoe-post-cover"> 
        
            <img src="https://i.loli.net/2019/01/13/5c3aec85a4343.jpg">
        
        <h1>何为Promise</h1>
    </div>
  <div class="nexmoe-post-meta">
    <a><i class="nexmoefont icon-calendar-fill"></i>2020年04月11日</a>
    <a><i class="nexmoefont icon-areachart"></i>913 字</a>
    <a><i class="nexmoefont icon-time-circle-fill"></i>大概 4 分钟</a>
    
      <a class="nexmoefont icon-appstore-fill -link" href="/categories/前端/">前端</a>
    
    
      <a class="nexmoefont icon-tag-fill -link" href="/tags/JS/">JS</a>
    
  </div>
  <article>
    <blockquote>
<p><strong>Promise</strong> 是进行异步操作的构造函数。<strong>Promise</strong> 对象用于表示一个异步操作的最终完成 (或失败), 及其结果值.</p>
</blockquote>
<a id="more"></a>
<h2 id="Promise"><a href="#Promise" class="headerlink" title="Promise"></a>Promise</h2><h3 id="参数"><a href="#参数" class="headerlink" title="参数"></a>参数</h3><p><code>Promise</code> 接收一个函数，并传入两个参数  <code>resolve</code>和<code>reject</code> ，分别表示异步操作执行<strong>成功后的回调</strong>函数和异步操作执行<strong>失败后的回调</strong>函数。</p>
<pre><code class="JavaScript">new Promise((resolve, reject) =&gt; {
    // 成功||将promise的状态改为fulfilled
    resolve()
    // 失败||将promise的状态改为rejected
    reject()
})
</code></pre>
<p>顾名思义是承诺，以后会发生的事情。</p>
<h3 id="描述"><a href="#描述" class="headerlink" title="描述"></a>描述</h3><p><code>Promise有</code>以下几种状态:</p>
<ul>
<li>pending: 初始状态，既不是成功，也不是失败状态。</li>
<li>fulfilled: 意味着操作成功完成。</li>
<li>rejected: 意味着操作失败。</li>
</ul>
<p><strong>Promise 的状态一旦发生变化，就会一直保持这个状态，是不可逆的状态。</strong></p>
<p>当<code>Promise</code>状态为<code>fulfilled</code>时 =&gt; 调用 <code>.then()</code> 方法</p>
<p>当<code>Promise</code>状态为<code>rejected</code>时 =&gt; 调用 <code>.catch()</code> 方法</p>
<h1 id="方法"><a href="#方法" class="headerlink" title="方法"></a>方法</h1><h3 id="then"><a href="#then" class="headerlink" title=".then()"></a>.then()</h3><p>当状态发生变化时，会调用.then() 绑定的函数方法。</p>
<pre><code class="JavaScript">Promise.then(
    success =&gt; {
        // 成功 resolve
    },
    error =&gt; {
        // 失败 reject
    }
)
</code></pre>
<h3 id="catch"><a href="#catch" class="headerlink" title=".catch()"></a>.catch()</h3><p>当 JS执行异常报错时，会执行.catch()捕获错误信息</p>
<pre><code class="JavaScript">Promise.catch(
    // 捕获错误
)
</code></pre>
<h3 id="all"><a href="#all" class="headerlink" title=".all()"></a>.all()</h3><pre><code class="JavaScript">var p = Promise.all([p1(), p2(), p3()])
</code></pre>
<p><code>all()</code>接受数组作为参数。</p>
<p>数组中的<code>p1,p2,p3</code>都是Promise的实例对象，p要变成<code>Resolved</code>状态需要<code>p1，p2，p3</code>状态都是<code>Resolved</code>。</p>
<p>如果<code>p1,p2,p3</code><strong>至少</strong>有一个状态是<code>Rejected</code>，p就会变成<code>Rejected</code>状态。</p>
<p><strong>即便只有一个是失败的状态，整体都会变成失败的状态</strong></p>
<h3 id="race"><a href="#race" class="headerlink" title=".race()"></a>.race()</h3><p>用法和 <code>.all()</code>方法一样，也是接收数组作为参数。</p>
<p>只要<code>p1、p2、p3</code>之中有一个实例率先改变状态，p的状态就跟着改变。</p>
<p>那个率先改变的 Promise 实例的返回值，就传递给p的回调函数,p的状态就会改变<code>Resolved</code>状态。</p>
<p><strong>即便只有一个是成功的状态，整体都会变成成功的状态</strong></p>
<h1 id="使用"><a href="#使用" class="headerlink" title="使用"></a>使用</h1><blockquote>
<p>主要应用场景我觉得是解决回调地狱而产生的。</p>
</blockquote>
<h3 id="基本例子"><a href="#基本例子" class="headerlink" title="基本例子"></a>基本例子</h3><pre><code class="JavaScript">// 一个简单的例子
let func1 = () =&gt; {
  return new Promise((resolve, reject) =&gt; {
    //  改变状态 =&gt; 成功 
    resolve(&#39;OK&#39;)
    // 改变状态 =&gt; 失败
    reject(&#39;Fail&#39;)
  })
 }

func1().then(
  success =&gt; {
    console.log(&#39;success&#39;, success)
  },
  error =&gt; {
    console.log(&#39;error&#39;, error)
  }
)
</code></pre>
<p>上述打印输出的结果是</p>
<pre><code class="JavaScript">success OK
</code></pre>
<p>原因是执行<code>resolve()</code>的时候，Promise 的状态已经发生了变化，所以后面的再执行 <code>reject()</code> 也是无法再次改变状态的。</p>
<p>在 <code>new Promise</code> 的时候传入两个参数，分别代表成功和失败的回调函数。</p>
<p>在状态发送改变后，就会调用<code>.then()</code>绑定的函数，<code>.then()</code>包含两个函数，第一个是成功的回调，第二个是失败的回调。</p>
<h3 id="进阶"><a href="#进阶" class="headerlink" title="进阶"></a>进阶</h3><p>现在有一个需求，也是我们项目中常见的需求:</p>
<pre><code>先请求A数据 =&gt; 再根据A数据中的ID =&gt; 再去请求B数据 ...
</code></pre><p>如果用传统的方式实现的，就很容易陷入<strong>回调地狱</strong>,如果层级一旦多的话，那代码看得令人头皮发麻。</p>
<pre><code class="JavaScript">$ajax({
    url: &#39;https:....&#39;,
    success: function () {
        $ajax({
            url: &#39;https:....&#39;,
            success: function () {
                .....
            }
        })
    }
})
</code></pre>
<p>现在改用 Promise 的方式实现一下一上需求</p>
<pre><code class="JavaScript">let func1 = () =&gt; {
  return new Promise((resolve, reject) =&gt; {
    //  改变状态 =&gt; 成功 
    resolve()
    console.log(&#39;A数据&#39;)
    // 改变状态 =&gt; 失败
    reject(&#39;Fail&#39;)
  })
 }

let fun2 = func1().then(
  success =&gt; {
    return new Promise((resolve, reject) =&gt; {
      resolve()
      console.log(&#39;B数据&#39;)
    })
  }
)

fun2.then(
  success =&gt; {
    console.log(&#39;成功的回调&#39;)
  }
)
</code></pre>
<p>上述代码运行后的结果是</p>
<pre><code class="JavaScript">A数据
B数据
成功的回调
</code></pre>
<p>这样就能保证能在 A 数据拿到的情况下才会去调用 B方法的请求。</p>

  </article>
  
    

  
  <section class="nexmoe-comment">
    <script id="dsq-count-scr" src="https://leegeing-cn.disqus.com/count.js" async></script>
<div id="disqus_thread"></div>
<script>
    var disqus_config = function () {
        this.page.url = 'https://mraing.github.io/2020/04/11/何为Promise/'; // Replace PAGE_URL with your page's canonical URL variable
        this.page.identifier = 'https://mraing.github.io/2020/04/11/何为Promise/'; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
    };
</script>
<script id="disqus-thread-script">
    (function() { // DON'T EDIT BELOW THIS LINE
        var d = document;
        var s = d.createElement('script');
        s.src = '//leegeing-cn.disqus.com/embed.js';
        s.setAttribute('data-timestamp', + new Date());
        (d.head || d.body).appendChild(s);
    })();
</script>

</section>
</div>
    </div>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/mdui@0.4.3/dist/js/mdui.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.4.1/dist/jquery.min.js"></script>
 
    <script src="https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js"></script>


 
    <script src="https://cdn.jsdelivr.net/npm/smoothscroll-for-websites@1.4.9/SmoothScroll.min.js"></script>


<script src="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@9.15.8/build/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>

<script src="/js/app.js?v=1627371788805"></script>
<script src="https://cdn.jsdelivr.net/npm/lazysizes@5.1.0/lazysizes.min.js"></script>


    <script type="text/javascript" src="https://cdn.jsdelivr.net/gh/xtaodada/xtaodada.github.io@0.0.2/copy.js"></script>

  





</body>

</html>
